<style lang="scss">
  .modify-avatar {
    input[type=file] {
      width: 0;
      height: 0;
      overflow: hidden;
      visibility: hidden;
    },
    .btn {
      display: block;
      margin: 20px auto;
      min-width: 220px;
    }
  }
</style>
<template>
  <div class="modify-avatar text-center">
    <div class="avatar-area">
      <div class="avatar-area-bg" v-bind:click="showModifyAvatar">
        <img v-bind:src="avatar" v-show="!imageUrl">
        <img v-bind:src="imageUrl" v-show="imageUrl">
      </div>
    </div>
    <div class="center">
      <input type="file" @change="onFileChange"/>
      <button type="button" class="btn btn-default"  v-on:click="chooseFile">选择文件</button>
      <button type="button" class="btn btn-primary" @click="upload">确定上传</button>
    </div>
  </div>
</template>
<script>
/**
 * @author guocailee
 */
/* global FileReader*/
import { updateAvatar } from 'src/store/actions/info'
export default {
  name: 'modifyAvatar',
  data() {
    let imageUrl = null
    return { imageUrl }
  },
  vuex: {
    getters: {
      avatar: ({ info }) => info.base.headPortrait
    },
    actions: {
      updateAvatar
    }
  },
  methods: {
    upload() {
      var self = this
      if (!this.files || !this.files.length) {
        this.$notify.error('请您先选择文件')
        return
      }
      this.$upload('file/uploadFileToLocal', this.files).then(data => {
        let fileName = data[0].payload.results.fileName
        return self.updateAvatar({
          fileName: fileName,
          imageUrl: self.imageUrl
        })
      }).then(data => {
        self.$notify.success('头像更改成功')
        self.$dispatch('closeModifyAvatar')
      }).catch(data => self.$notify.error(data))
    },
    chooseFile() {
      this.$el.getElementsByTagName('input')[0].click()
    },
    onFileChange(e) {
      this.files = e.target.files || e.dataTransfer.files
      if (!this.files.length) {
        return
      }
      this.createImage(this.files[0])
    },
    createImage(file) {
      var reader = new FileReader()
      var self = this
      reader.onload = (e) => {
        self.imageUrl = e.target.result
      }
      reader.readAsDataURL(file)
    },
    removeImage: function (e) {
      this.imageUrl = null
    }
  }
}
</script>